package com.mtons.mblog.modules.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.mtons.mblog.base.utils.ObjectConvertUtils;
import com.mtons.mblog.modules.service.PostSearchService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName: ESMqHandler
 * @Auther: Jerry
 * @Date: 2020/5/14 17:37
 * @Desctiption: 消息处理
 * @Version: 1.0
 */
@Component
public class ESMqHandler {

    private Logger log = LoggerFactory.getLogger(ESMqHandler.class);

    @Autowired
    private PostSearchService postSearchService;

    @RabbitListener(queues = RabbitConstant.ES_QUEUE)
    public void handler(Message message, Channel channel) throws IOException {
        ESMqMessage esMqMessage = (ESMqMessage) ObjectConvertUtils.ByteToObject(message.getBody());

        log.info("PostMqHandler -------> mq 收到一条消息： {}", JSONObject.toJSONString(esMqMessage));
        switch (esMqMessage.getAction()) {
            case ESMqMessage.CREATE_OR_UPDATE:
                postSearchService.createOrUpdateIndex(esMqMessage);
                break;
            case ESMqMessage.REMOVE:
                postSearchService.removeIndex(esMqMessage);
                break;
            default:
                log.error("没找到对应的消息类型，请注意！！ --》 {}", esMqMessage.toString());
                break;
        }
        // 手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
